import axios from 'axios'
import app from '@/config/app'
import Cookies from 'js-cookie'
import { Toast } from 'antd-mobile'

// 创建一个自定义axios对象
export const http = axios.create({
    baseURL: app.baseApi,
    timeout: app.timeout,
})

// 默认请求头设置
http.defaults.headers.common = {
    ...app.headers,
}

// 设置 token api 请求头
export const httpToken = token => {
    http.defaults.headers.common.Authorization = `Bearer ${token}`;
};

// 拦截器封装
export const middleware = history => {
    // 请求拦截器
    http.interceptors.request.use(request => {
        Toast.loading('加载中', 0)
        return request
    }, error => {
        return Promise.reject(error)
    })

    // 响应拦截器
    http.interceptors.response.use(response => {
        Toast.hide()
        
        return response
        // return response
    }, error => {
        console.log('goto...')
        Cookies.remove('token');
        history.replace('/register');
        Toast.hide()
        return Promise.reject(error);
    })
}

